<template>
	<div class="split-pane-wrapper" ref="outer">
		<div class="pane pane-left" :style="{width:leftOffsetPercent,paddingRight:`${this.triggerWidth/2}px`}">
			<!--<button @click="handleClick">Click</button>-->
			<slot name="left"></slot>
		</div>
		<div class="pane-trigger-con" @mousedown="handleMousedown"
			 :style="{left:triggerLeft, width:`${triggerWidth}px`}"></div>
		<div class="pane pane-right" :style="{left:leftOffsetPercent,paddingLeft:`${triggerWidth/2}px`}">
			<slot name="right"></slot>
		</div>
	</div>
</template>

<script>
	export default {
		name: "Split-pane",
		props: {
			/**
			 * 设置初始值
			 */
			value: {
				type: Number,
				default: 0.5
			},
			/**
			 * trigger的宽度
			 */
			triggerWidth: {
				type: Number,
				default: 8
			},
			/**
			 * trigger的最小值
			 */
			min: {
				type: Number,
				default: 0.1
			},
			/**
			 * trigger的最大值
			 */
			max: {
				type: Number,
				default: 0.9
			}
		},
		data() {
			return {
				// leftOffset: 0.3,
				canMove: false,
				initOffset: 0 // 初始化偏移量
			}
		},
		computed: {
			leftOffsetPercent() {
				return `${this.value * 100}%`;
			},
			triggerLeft() {
				return `calc(${this.value * 100}% - ${this.triggerWidth / 2}px)`;
			}
		},
		methods: {
			handleClick() {
				this.value -= 0.02;
			},
			/**
			 * 鼠标点击事件
			 * @param event
			 */
			handleMousedown(event) {
				document.addEventListener('mousemove', this.handleMousemove);
				document.addEventListener('mouseup', this.handleMouseup);
				this.initOffset = event.pageX - event.srcElement.getBoundingClientRect().left;
				this.canMove = true;
			},
			/**
			 * 鼠标拖动中间的trigger
			 * @param event
			 */
			handleMousemove(event) {
				if (!this.canMove) return;
				const outerRect = this.$refs.outer.getBoundingClientRect();
				// 偏移距离百分比
				let offsetPercent = (event.pageX - this.initOffset + this.triggerWidth / 2 - outerRect.left) / outerRect.width;
				if (offsetPercent < this.min) offsetPercent = this.min;
				if (offsetPercent > this.max) offsetPercent = this.max;
				// this.leftOffset = offsetPercent;
				// this.$emit('input', offsetPercent);
				this.$emit('update:value', offsetPercent);
			},
			/**
			 * 鼠标离开事件
			 */
			handleMouseup() {
				this.canMove = false;
			}
		}
	}
</script>

<style lang="less" scoped>
	.split-pane-wrapper {
		height: 100%;
		position: relative;

		.pane {
			position: absolute;
			top: 0;
			height: 100%;

			/*pane-left*/

			&-left {
				/*width: 30%;*/
				background-color: palevioletred;
			}

			&-right {
				right: 0;
				bottom: 0;
				/*left: 30%;*/
				background-color: paleturquoise;
			}

			&-trigger-con {
				height: 100%;
				background-color: palegoldenrod;
				position: absolute;
				top: 0;
				z-index: 10;
				user-select: none;
				cursor: col-resize;
			}
		}
	}
</style>
